<template>
    <div class="conversation-detail-container">
        <div class="page-header">
            <div class="header-left">
                <el-button @click="goBack">返回</el-button>
                <h2>对话详情</h2>
            </div>
            <div class="header-right">
                <el-button type="primary" @click="refreshMessages">刷新</el-button>
            </div>
        </div>

        <el-card class="conversation-info" v-if="conversation">
            <div class="info-item">
                <span class="label">会话ID：</span>
                <span>{{ conversation.id }}</span>
            </div>
            <div class="info-item">
                <span class="label">用户ID：</span>
                <span>{{ conversation.userId }}</span>
            </div>
            <div class="info-item">
                <span class="label">会话标题：</span>
                <span>{{ conversation.title }}</span>
            </div>
            <div class="info-item">
                <span class="label">创建时间：</span>
                <span>{{ formatDateTime(conversation.createdAt) }}</span>
            </div>
            <div class="info-item">
                <span class="label">更新时间：</span>
                <span>{{ formatDateTime(conversation.updatedAt) }}</span>
            </div>
            <div class="info-item">
                <span class="label">状态：</span>
                <el-tag :type="getStatusType(conversation.status)">
                    {{ getStatusText(conversation.status) }}
                </el-tag>
            </div>
        </el-card>

        <div class="messages-container" v-loading="loading">
            <div class="message-list">
                <div v-for="(message, index) in messages" :key="index" class="message-item"
                    :class="{ 'user-message': message.role === 'user' }">
                    <div class="message-header">
                        <div class="message-role">
                            <el-tag size="small" :type="message.role === 'user' ? 'primary' : 'success'">
                                {{ message.role === 'user' ? '用户' : 'AI助手' }}
                            </el-tag>
                        </div>
                        <div class="message-time">{{ formatDateTime(message.createdAt) }}</div>
                    </div>
                    <div class="message-content" v-if="message.contentType === 'text'">
                        <pre>{{ message.content }}</pre>
                    </div>
                    <div class="message-content" v-else-if="message.contentType === 'image'">
                        <img :src="message.content" alt="图片消息" class="message-image"
                            @click="previewImage(message.content)" />
                    </div>
                </div>

                <div v-if="messages.length === 0" class="no-messages">
                    <el-empty description="暂无消息记录" />
                </div>
            </div>

            <div class="load-more" v-if="hasMoreMessages">
                <el-button type="text" @click="loadMoreMessages" :loading="loadingMore">加载更多</el-button>
            </div>
        </div>

        <el-dialog title="图片预览" v-model="previewVisible" width="50%">
            <img :src="previewUrl" alt="图片预览" class="preview-image" />
        </el-dialog>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import chatApi from '@/api/chat.js'

export default {
    name: 'ConversationDetail',
    data() {
        return {
            conversationId: null,
            conversation: null,
            messages: [],
            loading: false,
            loadingMore: false,
            currentPage: 1,
            pageSize: 20,
            total: 0,
            hasMoreMessages: false,
            previewVisible: false,
            previewUrl: ''
        }
    },
    created() {
        this.conversationId = this.$route.params.id
        if (!this.conversationId) {
            ElMessage.error('会话ID不能为空')
            this.goBack()
            return
        }
        this.fetchConversation()
        this.fetchMessages()
    },
    methods: {
        goBack() {
            this.$router.push({ name: 'ConversationList' })
        },
        fetchConversation() {
            this.loading = true
            chatApi.getConversation(this.conversationId)
                .then(response => {
                    if (response.code === 200) {
                        const data = response.data;
                        if (data) {
                            this.conversation = {
                                id: data.id,
                                userId: data.user_id,
                                title: data.title || '无标题会话',
                                createdAt: data.created_at,
                                updatedAt: data.updated_at,
                                status: data.status
                            };
                        } else {
                            this.conversation = null;
                            ElMessage.error('获取会话详情失败：数据为空');
                            this.goBack();
                        }
                    } else {
                        ElMessage.error(response.message || '获取会话详情失败')
                        this.goBack()
                    }
                })
                .catch(error => {
                    console.error('获取会话详情失败:', error)
                    ElMessage.error('获取会话详情失败')
                    this.goBack()
                })
                .finally(() => {
                    this.loading = false
                })
        },
        fetchMessages() {
            this.loading = true
            const params = {
                conversation_id: this.conversationId,
                page: this.currentPage,
                page_size: this.pageSize
            }

            chatApi.getMessages(params)
                .then(response => {
                    if (response.code === 200) {
                        let messageList = [];
                        let totalCount = 0;
                        
                        if (Array.isArray(response.data)) {
                            messageList = response.data;
                            totalCount = response.data.length;
                        } else if (response.data && response.data.list) {
                            messageList = response.data.list;
                            totalCount = response.data.total || 0;
                        }
                        
                        this.messages = messageList.map(msg => ({
                            id: msg.id,
                            conversationId: msg.conversation_id,
                            userId: msg.user_id,
                            role: msg.role,
                            content: msg.content,
                            contentType: msg.content_type || 'text',
                            createdAt: msg.created_at,
                            status: msg.status
                        }));
                        
                        this.total = totalCount;
                        this.hasMoreMessages = this.currentPage * this.pageSize < this.total;
                    } else {
                        ElMessage.error(response.message || '获取消息列表失败')
                    }
                })
                .catch(error => {
                    console.error('获取消息列表失败:', error)
                    ElMessage.error('获取消息列表失败')
                })
                .finally(() => {
                    this.loading = false
                })
        },
        loadMoreMessages() {
            if (this.loadingMore) return

            this.loadingMore = true
            this.currentPage++

            const params = {
                conversation_id: this.conversationId,
                page: this.currentPage,
                page_size: this.pageSize
            }

            chatApi.getMessages(params)
                .then(response => {
                    if (response.code === 200) {
                        let messageList = [];
                        let totalCount = this.total;
                        
                        if (Array.isArray(response.data)) {
                            messageList = response.data;
                        } else if (response.data && response.data.list) {
                            messageList = response.data.list;
                            totalCount = response.data.total || this.total;
                        }
                        
                        const newMessages = messageList.map(msg => ({
                            id: msg.id,
                            conversationId: msg.conversation_id,
                            userId: msg.user_id,
                            role: msg.role,
                            content: msg.content,
                            contentType: msg.content_type || 'text',
                            createdAt: msg.created_at,
                            status: msg.status
                        }));
                        
                        this.messages = [...this.messages, ...newMessages];
                        this.total = totalCount;
                        this.hasMoreMessages = this.currentPage * this.pageSize < this.total;
                    } else {
                        ElMessage.error(response.message || '加载更多消息失败')
                        this.currentPage-- // 恢复页码
                    }
                })
                .catch(error => {
                    console.error('加载更多消息失败:', error)
                    ElMessage.error('加载更多消息失败')
                    this.currentPage-- // 恢复页码
                })
                .finally(() => {
                    this.loadingMore = false
                })
        },
        refreshMessages() {
            this.currentPage = 1
            this.fetchMessages()
        },
        formatDateTime(dateTime) {
            if (!dateTime) return '-'
            const date = new Date(dateTime)
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
        },
        getStatusType(status) {
            switch (status) {
                case 1: return 'success'  // 活跃
                case 2: return 'info'     // 归档
                case 3: return 'danger'   // 删除
                default: return 'info'
            }
        },
        getStatusText(status) {
            switch (status) {
                case 1: return '活跃'
                case 2: return '归档'
                case 3: return '已删除'
                default: return '未知'
            }
        },
        previewImage(url) {
            this.previewUrl = url
            this.previewVisible = true
        }
    }
}
</script>

<style scoped>
.conversation-detail-container {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.header-left {
    display: flex;
    align-items: center;
}

.header-left h2 {
    margin-left: 15px;
    margin-bottom: 0;
}

.conversation-info {
    margin-bottom: 20px;
}

.info-item {
    margin-bottom: 10px;
}

.info-item .label {
    font-weight: bold;
    margin-right: 10px;
}

.messages-container {
    background-color: #f5f7fa;
    border-radius: 4px;
    padding: 20px;
    min-height: 400px;
}

.message-list {
    display: flex;
    flex-direction: column;
}

.message-item {
    margin-bottom: 20px;
    max-width: 80%;
    background-color: #fff;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-message {
    align-self: flex-end;
    background-color: #ecf5ff;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.message-content {
    word-break: break-word;
}

.message-content pre {
    white-space: pre-wrap;
    margin: 0;
    font-family: inherit;
}

.message-image {
    max-width: 100%;
    max-height: 300px;
    cursor: pointer;
}

.no-messages {
    display: flex;
    justify-content: center;
    padding: 40px 0;
}

.load-more {
    text-align: center;
    margin-top: 20px;
}

.preview-image {
    max-width: 100%;
    max-height: 80vh;
    display: block;
    margin: 0 auto;
}
</style>